package com.example.ConnES;

import android.util.Log;
import com.google.gson.Gson;
import lombok.SneakyThrows;
import okhttp3.*;
import org.jetbrains.annotations.NotNull;

import java.io.IOException;
import java.nio.charset.Charset;


public class parseXml {
    private static final String TAG="parsejson";
    public static final MediaType JSON= MediaType.get("application/json; charset=utf-8");
    private static final String url="http://10.206.6.31:8080";
    private static OkHttpClient okHttpClient=new OkHttpClient();
    static Cipher cip=new Cipher();
    //get请求
    public static Cipher sendrequestWithOkHttp(){
        new Thread() {
            @SneakyThrows
            @Override
            public void run() {

                Request request = new Request.Builder().url(url+"/crypto").build();
                Call call = okHttpClient.newCall(request);
                try{
                    Response response = call.execute();
                    String responseData = response.body().string();
                    Gson gson = new Gson();
                    cip = gson.fromJson(responseData, Cipher.class);
                }catch(Exception e){
                    Log.i(TAG,"error"+e);
                }

            }
        }.start();
        return cip;
    }
    public static void sendTest(){
        new Thread(){
            @Override
            public void run() {
                Request request = new Request.Builder().url("https://www.httpbin.org/get?a=1&b=2").build();
                Call call = okHttpClient.newCall(request);
                try {
                    Response execute = call.execute();
                    Log.i(TAG,"response:"+execute.body().string());
                } catch (IOException e) {
                    Log.i(TAG,"error"+e);
                };

            }
        }.start();
    }
    //post请求
    public static void sendpost(){
        Cipher cp=new Cipher("2123",12,13);
        Gson gson=new Gson();
        //javabean转化为json
        String s = gson.toJson(cp);
        RequestBody formBody=RequestBody.create(s,JSON);
        Request request=new Request.Builder().url(url+"/crypto/upload").post(formBody).build();
        Call call=okHttpClient.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(@NotNull Call call, @NotNull IOException e) {
                Log.i("mainactivity","error"+request.body().toString());

            }

            @Override
            public void onResponse(@NotNull Call call, @NotNull Response response) throws IOException {

            }
        });

    }

}
